#!/bin/bash
# cat list2.txt | xargs -P10 -I'{}' bash -c 'curl --user XXX: https://abf.rosalinux.ru/api/v1/build_lists/{}.json | jq . > jsons/{}.json || echo {} > failed.list'
# https://rosa-abf.github.io/abf/api/v1/build_lists/
# Запускать масс-билд с доп. параметром сборки RPM: --version
# (тогда собирается только SRPM)

set -e
set -u
set -a

F="$(mktemp)"
trap 'unlink "$F"' EXIT

# $1: path to json file
_download(){
	if [ "$(jq -r '.build_list.packages[0].type' "$1")" != source ]; then
		return 1
	fi
	local arch
	arch="$(jq -r '.build_list.arch.name' "$1")"
	test -n "$arch"
	local url
	url="$(jq -r '.build_list.packages[0].url' "$1")"
	test -n "$url"
	mkdir -p srpms_"$arch"
	pushd srpms_"$arch"
	wget --content-disposition "$url"
	popd
}

_cmp(){
	local line
	line="$1"
	arch="$(echo "$line" | awk -F/ '{print $1}' | sed -e 's,srpms_,,')"
	file="$(basename "$line")"
	test -n "$arch"
	arches=()
	case "$arch" in
		aarch64 ) arches=(x86_64 i686) ;;
		i686 ) arches=(x86_64 aarch64) ;;
		x86_64 ) arches=(aarch64 i686) ;;
	esac
	hash1="$(rpm -qp "$line" --dump | sort -u | awk '{print $4}' | md5sum | awk '{print $1}')"
	if test -f srpms_"${arches[0]}"/"$file"
		then hash2="$(rpm -qp srpms_"${arches[0]}"/"$file" --dump | sort -u | awk '{print $4}' | md5sum | awk '{print $1}')"
		else hash2="null"
	fi
	if test -f srpms_"${arches[1]}"/"$file"
		then hash3="$(rpm -qp srpms_"${arches[1]}"/"$file" --dump | sort -u | awk '{print $4}' | md5sum | awk '{print $1}')"
		else hash3="null"
	fi
	if ! { [ "$hash1" = "$hash2" ] && [ "$hash1" = "$hash3" ] && [ "$hash2" = "$hash3" ] ;}; then
		flock "$F" bash -c "grep -q ^$file diff.list || echo $file $hash1 $hash2 $hash3 >> diff.list"
	fi
}

ls jsons/*.json | xargs -P20 -I'{}' bash -c '_download {} || echo {} >> failed.list'
ls srpms_*/*.src.rpm  | xargs -P4 -I'{}' bash -c '_cmp {}'
